import { VerifyClientCallbackAsync } from "ws";
import http from 'http';
import jwt from "jsonwebtoken";

const verifyClient: VerifyClientCallbackAsync = (info, done) => {
    const token = getTokenFromRequest(info.req);
    if (!token) {
        done(false, 401, 'Unauthorized - No token provided');
        return;
    }
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET) as JwtPayload;
        info.req.auth = decoded;
        done(true);
    } catch (err) {
        done(false, 401, 'Unauthorized - Invalid token');
    }
}

function getTokenFromRequest(req: http.IncomingMessage): string | null {
    if (req.url && req.url.includes('token=')) {
        const tokenParam = req.url.split('token=')[1].split('&')[0];
        return tokenParam;
    }
    const authHeader = req.headers['authorization'];
    if (authHeader && authHeader.startsWith('Bearer ')) {
        return authHeader.split(' ')[1];
    }
    return null;
}
export default verifyClient;